package com.xtedu.examproject.controller;

import com.google.gson.Gson;
import com.xtedu.examproject.entity.Classes;
import com.xtedu.examproject.entity.Student;
import com.xtedu.examproject.service.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.*;
import java.sql.Date;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@MultipartConfig(
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 10,
        fileSizeThreshold = 1024 * 1024 * 1
)
@WebServlet("/stumanage/*")
public class StuManageServlet extends HttpServlet {

    private StudentService stuService;
    private ClassesService classesService;

    public void init() {
        stuService = new StudentService();
        classesService = new ClassesService();
    }

    /**
     * 提取URL中的action参数（纯工具方法，不执行业务逻辑）
     */
    private String extractActionFromRequest(HttpServletRequest request) {
        // 从URL中提取action参数,默认如果是null,则返回delstumanage,如果不是，则返回对应的 action
        String action = null;
        String pathInfo = request.getPathInfo();

        if (pathInfo != null && pathInfo.length() > 1) {
            action = pathInfo.substring(1);
        } else {
            String uri = request.getRequestURI();
            String contextPath = request.getContextPath();
            String path = uri.substring(contextPath.length());

            int lastSlashIndex = path.lastIndexOf('/');
            if (lastSlashIndex >= 0 && lastSlashIndex < path.length() - 1) {
                action = path.substring(lastSlashIndex + 1);
            }
        }
        return action;
    }

    /**
     * 路由GET请求到相应的显示方法
     */
    private void routeGetRequest(String action, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        switch (action) {
            case "update":
                handleEditGet(request, response); // 显示编辑表单
                break;
            case "delete":
                handleDeleteGet(request, response); // 显示删除表单
                break;
            case "studentSearch":
                handleSearchGet(request, response);
                break;
            default:
                // 默认显示删除页面
                handleDeleteGet(request, response); // 显示删除表单
                break;
        }
    }

    /**
     * 路由POST请求到相应的处理方法
     */
    private void routePostRequest(String action, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        switch (action) {
            case "add":
                handleaddPost(request, response);// 处理添加表单提交
                break;
            case "update":
                handleEditPost(request, response);
                break;
            case "delete":
                handleDeletePost(request, response);
                break;
            case "batchAdd":
                handleBatchAddPost(request, response);
                break;
            default:
                handleDeletePost(request, response);
                break;
        }
    }


    private void handleaddPost(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 首先设置字符编码
        request.setCharacterEncoding("UTF-8");

        // 然后设置正确的响应类型和编码
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            // 详细的调试信息 - 打印所有接收到的参数
            System.out.println("=== 开始处理添加学生请求 ===");
            java.util.Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);
                System.out.println("参数 " + paramName + " = '" + paramValue + "'");
            }

            // 使用request.getParameter获取表单数据
            String idCard = request.getParameter("idCard");
            String name = request.getParameter("name");
            String genderStr = request.getParameter("gender");
            String classIDStr = request.getParameter("classID");
            String ageStr = request.getParameter("age");
            String eduBackground = request.getParameter("eduBackground");
            String phone = request.getParameter("phone");

            // 检查是否有任何参数为null
            if (idCard == null || name == null || genderStr == null ||
                    classIDStr == null || ageStr == null ||
                    eduBackground == null || phone == null) {

                System.out.println("错误：有参数为null");
                result.put("success", false);
                result.put("message", "缺少参数: " +
                        (idCard == null ? "idCard " : "") +
                        (name == null ? "name " : "") +
                        (genderStr == null ? "gender " : "") +
                        (classIDStr == null ? "classID " : "") +
                        (ageStr == null ? "age " : "") +
                        (eduBackground == null ? "eduBackground " : "") +
                        (phone == null ? "phone " : ""));
                out.print(new Gson().toJson(result));
                return;
            }

            // 检查空字符串
            if (idCard.trim().isEmpty() || name.trim().isEmpty() || genderStr.trim().isEmpty() ||
                    classIDStr.trim().isEmpty() || ageStr.trim().isEmpty() ||
                    eduBackground.trim().isEmpty() || phone.trim().isEmpty()) {

                System.out.println("错误：有参数为空字符串");
                result.put("success", false);
                result.put("message", "所有字段都是必填的");
                out.print(new Gson().toJson(result));
                return;
            }

            // 转换数据类型
            boolean gender = "true".equals(genderStr);
            int classID = Integer.parseInt(classIDStr);
            int age = Integer.parseInt(ageStr);

            // 创建学生对象并设置属性
            Student stu = new Student();
            stu.setIdCard(idCard);
            stu.setName(name);
            stu.setGender(gender);
            stu.setClassID(classID);
            stu.setAge(age);
            stu.setEduBackground(eduBackground);
            stu.setPhone(phone);
            stu.setCreateDate(new Date(System.currentTimeMillis()));

            // 打印学生信息
            System.out.println("添加学生信息: " + stu.getName());
            System.out.println("班级ID: " + stu.getClassID());
            System.out.println("年龄: " + stu.getAge());

            // 插入学生记录
            int id = stuService.insertStudent(stu);
            result.put("success", id > 0);
            result.put("message", id > 0 ? "添加成功" : "添加失败");

        } catch (NumberFormatException e) {
            System.out.println("数字格式异常: " + e.getMessage());
            result.put("success", false);
            result.put("message", "数字格式错误: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("服务器异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
        } finally {
            out.print(new Gson().toJson(result));
            out.flush();
            out.close();
        }
    }

    private void handleEditGet(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String idParam = request.getParameter("id");
            if (idParam != null && !idParam.trim().isEmpty()) {
                int id = Integer.parseInt(idParam.trim());
                Student student = stuService.findStudentById(id);

                if (student != null) {
                    // 使用Gson将学生对象转换为JSON
                    out.print(new Gson().toJson(student));
                } else {
                    out.print("{}"); // 返回空对象
                }
            } else {
                out.print("{}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{}");
        }

    }

    private void handleEditPost(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            // 获取参数

            String idCard = request.getParameter("idCard");
            String name = request.getParameter("name");
            boolean gender = "true".equals(request.getParameter("gender"));
            int classID = Integer.parseInt(request.getParameter("classID"));
            int age = Integer.parseInt(request.getParameter("age"));
            String eduBackground = request.getParameter("eduBackground");
            String phone = request.getParameter("phone");

            // 数据验证
            if (idCard == null || idCard.trim().isEmpty() ||
                    name == null || name.trim().isEmpty() ||
                    eduBackground == null || eduBackground.trim().isEmpty() ||
                    phone == null || phone.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "所有字段都是必填的");
                out.print(new Gson().toJson(result));
                return;
            }

            // 创建学生对象并设置属性
            id = Integer.parseInt(request.getParameter("id"));
            Student stu = stuService.findStudentById(id);
            stu.setIdCard(idCard);
            stu.setName(name);
            stu.setGender(gender);
            stu.setClassID(classID);
            stu.setAge(age);
            stu.setEduBackground(eduBackground);
            stu.setPhone(phone);
            // 更新学生记录
            boolean success = stuService.updateStudent(stu) > 0;
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");

        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "数字格式错误: " + e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
        } finally {
            out.print(new Gson().toJson(result));
        }

    }

    private void handleDeleteGet(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            List<Classes> classes = classesService.findAllClasses();
            List<Student> students = stuService.findAllStudent();
            request.setAttribute("classes", classes);
            request.setAttribute("menuItems", students);
            // 转发到JSP页面
            request.getRequestDispatcher("/WEB-INF/views/delstumanage.jsp").forward(request, response);
        } catch (Exception e) {
            request.setAttribute("errorMessage", "获取学生数据失败: " + e.getMessage());
        }
    }

    private void handleDeletePost(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("application/x-www-form-urlencoded");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String idParam = request.getParameter("id");
            if (idParam != null && !idParam.trim().isEmpty()) {
                int id = Integer.parseInt(idParam.trim());// 获取菜单ID
                Student student = stuService.findStudentById(id);
                if (student != null) {
                    boolean success = stuService.deleteStudent(student) > 0;
                    out.write("{\"success\": " + success + "}");
                } else {
                    out.write("{\"success\": false, \"message\": \"信息不存在\"}");
                }
            } else {
                out.write("{\"success\": false, \"message\": \"缺少参数\"}");
            }

        } catch (Exception e) {
            log("处理删除学生信息请求时发生错误", e);
            out.write("{\"success\": false, \"message\": \"服务器错误\"}");
        }

    }

    //多条件查询
    private void handleSearchGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            // 正确获取各个参数
            String searchKey = request.getParameter("idCard"); // 搜索条件

            // 教育背景
            String eduBackground = request.getParameter("eduBackground");

            // 年龄处理
            String age = request.getParameter("age");

            // 性别处理（前端传的是 "1"/"0"）
            String genderString = request.getParameter("gender");
            int gender = -1;
            if (genderString != null && !genderString.trim().isEmpty()) {
                if ("1".equals(genderString)) {
                    gender = 1;
                } else if ("0".equals(genderString)) {
                    gender = 0;
                }
            }
            // 班级ID（安全处理空值）
            String classIDStr = request.getParameter("classID");
            List<Student> students;
            students = stuService.searchStudents(searchKey, gender, classIDStr, eduBackground);
            // 设置请求属性
            request.setAttribute("menuItems", students);
            request.setAttribute("classes", classesService.findAllClasses());

            // 转发到JSP
            request.getRequestDispatcher("/WEB-INF/views/delstumanage.jsp").forward(request, response);

        } catch (Exception e) {
            // 记录完整错误日志
            e.printStackTrace();

            // 设置错误信息并重新转发
            request.setAttribute("errorMessage", "获取学生数据失败: " + e.getMessage());
            request.setAttribute("classes", classesService.findAllClasses()); // 确保班级数据存在
            request.getRequestDispatcher("/WEB-INF/views/delstumanage.jsp").forward(request, response);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //默认是get请求
        String action = extractActionFromRequest(request);
        try {
            routeGetRequest(action, request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = extractActionFromRequest(request);
        try {
            routePostRequest(action, request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 批量添加处理方法
    // 修改 handleBatchAddPost 方法，保存原始文件名
    private void handleBatchAddPost(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查是否为 multipart 请求
            if (!request.getContentType().toLowerCase().startsWith("multipart/")) {
                result.put("success", false);
                result.put("message", "请求类型错误");
                out.print(new Gson().toJson(result));
                return;
            }

            java.io.File uploadedFile = null;
            boolean hasHeader = true;
            String originalFileName = null;

            // 获取所有 part
            Collection<Part> parts = request.getParts();

            for (Part part : parts) {
                String partName = part.getName();

                if (partName.equals("hasHeader")) {
                    // 处理普通表单字段
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(part.getInputStream(), "UTF-8"));
                    hasHeader = "true".equals(reader.readLine());
                    reader.close();
                } else if (partName.equals("file") && part.getSize() > 0) {
                    // 处理上传的文件
                    originalFileName = part.getSubmittedFileName(); // 获取原始文件名
                    uploadedFile = java.io.File.createTempFile("student_upload_", ".tmp");

                    try (InputStream input = part.getInputStream();
                         FileOutputStream output = new FileOutputStream(uploadedFile)) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = input.read(buffer)) > 0) {
                            output.write(buffer, 0, length);
                        }
                    }
                }
            }

            if (uploadedFile == null) {
                result.put("success", false);
                result.put("message", "未找到上传文件");
                out.print(new Gson().toJson(result));
                return;
            }

            if (originalFileName == null) {
                result.put("success", false);
                result.put("message", "无法获取文件名");
                out.print(new Gson().toJson(result));
                return;
            }

            // 解析文件并批量插入，传入原始文件名
            BatchImportResult importResult = parseAndImportStudents(uploadedFile, hasHeader, originalFileName);

            // 删除临时文件
            uploadedFile.delete();

            result.put("success", true);
            result.put("message", "批量导入完成");
            result.put("successCount", importResult.getSuccessCount());
            result.put("failCount", importResult.getFailCount());
            result.put("errors", importResult.getErrors());

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
        } finally {
            out.print(new Gson().toJson(result));
        }
    }

    // 解析和导入学生数据
    // 修改 parseAndImportStudents 方法，添加原始文件名参数
    private BatchImportResult parseAndImportStudents(java.io.File file, boolean hasHeader, String originalFileName) {
        BatchImportResult result = new BatchImportResult();
        String fileName = originalFileName.toLowerCase(); // 使用原始文件名

        try {
            if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
                parseExcelFile(file, hasHeader, result);
            } else if (fileName.endsWith(".csv")) {
                parseCsvFile(file, hasHeader, result);
            } else {
                result.addError("不支持的文件格式: " + originalFileName);
            }
        } catch (Exception e) {
            result.addError("文件解析错误: " + e.getMessage());
        }

        return result;
    }

    // 解析Excel文件
    private void parseExcelFile(java.io.File file, boolean hasHeader, BatchImportResult result)
            throws Exception {
        try (java.io.FileInputStream fis = new java.io.FileInputStream(file);
             org.apache.poi.ss.usermodel.Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(fis)) {

            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
            java.util.Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();

            int rowNum = 0;
            while (rowIterator.hasNext()) {
                org.apache.poi.ss.usermodel.Row row = rowIterator.next();
                rowNum++;

                // 跳过表头
                if (hasHeader && rowNum == 1) {
                    continue;
                }

                // 读取行数据
                if (row.getPhysicalNumberOfCells() >= 7) {
                    String idCard = getCellStringValue(row.getCell(0));
                    String name = getCellStringValue(row.getCell(1));
                    String genderStr = getCellStringValue(row.getCell(2));
                    String classIDStr = getCellStringValue(row.getCell(3));
                    String ageStr = getCellStringValue(row.getCell(4));
                    String eduBackground = getCellStringValue(row.getCell(5));
                    String phone = getCellStringValue(row.getCell(6));

                    // 导入学生数据
                    importStudentData(idCard, name, genderStr, classIDStr, ageStr, eduBackground, phone, result);
                }
            }
        }
    }

    // 解析CSV文件
    private void parseCsvFile(java.io.File file, boolean hasHeader, BatchImportResult result)
            throws Exception {
        try (java.io.BufferedReader reader = new java.io.BufferedReader(
                new java.io.InputStreamReader(new java.io.FileInputStream(file), "UTF-8"))) {

            String line;
            int lineNum = 0;
            while ((line = reader.readLine()) != null) {
                lineNum++;

                // 跳过表头
                if (hasHeader && lineNum == 1) {
                    continue;
                }

                // 解析CSV行
                String[] values = line.split(",");
                if (values.length >= 7) {
                    importStudentData(
                            values[0].trim(), values[1].trim(), values[2].trim(),
                            values[3].trim(), values[4].trim(), values[5].trim(),
                            values[6].trim(),
                            result
                    );
                }
            }
        }
    }

    // 导入单条学生数据
    private void importStudentData(String idCard, String name, String genderStr,
                                   String classIDStr, String ageStr, String eduBackground,
                                   String phone, BatchImportResult result) {
        try {
            // 数据验证
            if (idCard == null || idCard.trim().isEmpty() ||
                    name == null || name.trim().isEmpty() ||
                    genderStr == null || genderStr.trim().isEmpty() ||
                    classIDStr == null || classIDStr.trim().isEmpty() ||
                    ageStr == null || ageStr.trim().isEmpty() ||
                    eduBackground == null || eduBackground.trim().isEmpty() ||
                    phone == null || phone.trim().isEmpty()) {
                result.addError("第" + (result.getTotalCount() + 1) + "行: 缺少必要字段");
                return;
            }

            // 转换数据类型
            boolean gender = "男".equals(genderStr.trim());
            int classID = Integer.parseInt(classIDStr.trim());
            int age = Integer.parseInt(ageStr.trim());

            // 创建学生对象
            Student student = new Student();
            student.setIdCard(idCard);
            student.setName(name);
            student.setGender(gender);
            student.setClassID(classID);
            student.setAge(age);
            student.setEduBackground(eduBackground);
            student.setPhone(phone);
            student.setCreateDate(new java.sql.Date(System.currentTimeMillis()));

            // 插入数据库
            int id = stuService.insertStudent(student);
            if (id > 0) {
                result.incrementSuccessCount();
            } else {
                result.addError("第" + (result.getTotalCount() + 1) + "行: 插入数据库失败");
            }

        } catch (NumberFormatException e) {
            result.addError("第" + (result.getTotalCount() + 1) + "行: 数字格式错误");
        } catch (Exception e) {
            result.addError("第" + (result.getTotalCount() + 1) + "行: " + e.getMessage());
        }
    }

    // 辅助方法：获取单元格字符串值
    private String getCellStringValue(org.apache.poi.ss.usermodel.Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    return new java.text.SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
                } else {
                    return String.valueOf((int) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    // 批量导入结果类
    class BatchImportResult {
        private int successCount = 0;
        private int failCount = 0;
        private java.util.List<String> errors = new java.util.ArrayList<>();

        public void incrementSuccessCount() {
            successCount++;
        }

        public void addError(String error) {
            errors.add(error);
            failCount++;
        }

        public int getSuccessCount() {
            return successCount;
        }

        public int getFailCount() {
            return failCount;
        }

        public int getTotalCount() {
            return successCount + failCount;
        }

        public java.util.List<String> getErrors() {
            return errors;
        }
    }

}
